<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Cache;

class Config extends Base
{
    protected function getTypeAttr($value)
    {
        return get_config_type($value);
    }

    protected function getGroupAttr($value)
    {
        return get_config_group($value);
    }

    public static function saveGroup($config, $admin): array
    {
        try {
            if ($config && is_array($config)) {
                $msg = '';
                foreach ($config as $name => $value) {
                    $info = parent::where('name', $name)->field('id,title,type,value,format,suffix')->find();
                    if (!$info) {
                        continue;
                    }
                    if ($info['suffix'] == '%') {
                        $value = $value / 100;
                    }
                    switch ($info->getData('type')) {
                        case 7:
                            $value = set_layDate($value, $info['format']);
                            break;
                        case 9:
                            $start = $value;
                            $end = $config[$name . '_2'];
                            if ($info['suffix'] == '%') {
                                $end = $end / 100;
                            }
                            //区间格式目前只支持数字
                            if ($end < $start) {
                                throw new \Exception('开始值不能大于结束值');
                            }
                            $value = $start . ',' . $end;
                            unset($config[$name . '_2']);
                            break;
                        case 10:
                            $value = implode(',', $value);
                            break;
                    }
                    if ($info->getData('type') == 6) {
                        if ($info['value'] != $value) {
                            $msg .= '修改【' . $info['title'] . '】由<a target="_blank" href="' . $info['value'] . '">
                        <img style="width: 20px" src="' . $info['value'] . '"/></a>修改为<a target="_blank" href="' . $value . '">
                        <img style="width: 20px" src="' . $value . '"/></a>，';
                        }
                    } else {
                        if ($info['value'] != $value) {
                            $msg .= '修改【' . $info['title'] . '】由【' . $info['value'] . '】修改为【' . $value . '】，';
                        }
                    }
                    parent::update(['value' => $value], ['id' => $info['id']]);
                }
            }
            if ($msg) {
                Logs::adds($msg, $admin->id, $admin->admin_name);
            }
            Cache::delete('system');

        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '操作成功'];
    }
}